package com.lwj.liwanjia.view.activity.login;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.XiuGaiMiMaSure;
import com.lwj.liwanjia.bean.XiuGaiMiMaYZM;
import com.lwj.liwanjia.config.URLConstant;
import com.lwj.liwanjia.utils.RetrofitHelper;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.TimeCount;
import com.lwj.liwanjia.utils.TimeCountDown1;

import java.io.IOException;

import butterknife.OnTextChanged;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 001 on 2017/9/5.
 */

public class ForgetSureActivity extends BaseActivity implements View.OnClickListener {

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    Toast.makeText(ForgetSureActivity.this, "修改密码的验证码接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(ForgetSureActivity.this, "验证码获取失败", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(ForgetSureActivity.this, "验证码获取成功", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(ForgetSureActivity.this, "修改密码接口有问题", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(ForgetSureActivity.this, "修改密码失败", Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    Toast.makeText(ForgetSureActivity.this, "修改密码成功", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 6:
                    Toast.makeText(ForgetSureActivity.this, "手机号码有误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private TextView tv_title;//头布局标题
    private TextView tv_back;//头布局左边的返回按钮
    private TextView tv_phone;//提示手机号码
    private EditText et_yanZhengMa;//验证码
    private EditText et_password;//密码
    private Button bt_sure;//确认
    private TextView tv_yanZhengMa;//发送验证码
    private String phoneNumber;//手机号码
    private String yanZhengMa;
    private TimeCount count;
    private ImageView ivYincang;
    private int click = 0;//密码是否隐藏，0代表是

    @Override
    protected void initView() {

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back = (TextView) findViewById(R.id.tv_left);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        et_yanZhengMa = (EditText) findViewById(R.id.et_yanZhengMa);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_sure = (Button) findViewById(R.id.bt_sure);
        tv_yanZhengMa = (TextView) findViewById(R.id.tv_yanZhengMa);
        ivYincang = (ImageView) findViewById(R.id.iv_yincang);

        tv_back.setOnClickListener(this);
        bt_sure.setOnClickListener(this);
        tv_yanZhengMa.setOnClickListener(this);
        ivYincang.setOnClickListener(this);

        //初始化UI
        tv_back.setText("返回");
        tv_back.setVisibility(View.VISIBLE);
        tv_title.setText("忘记密码");
        count = new TimeCount(60000, 1000, tv_yanZhengMa);
        count.start();
    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        phoneNumber = intent.getStringExtra("Number");

        //隐藏手机号码中间几位
        String phoneFirst = phoneNumber.substring(0, 3);
        String phoneEnd = phoneNumber.substring(phoneFirst.length() + 4, phoneNumber.length());
        String phoneNew = phoneFirst + "****" + phoneEnd;
        String resultPhone = "短信验证码已发送到绑定手机" + phoneNew;
        tv_phone.setText(resultPhone);

        //连接接口,获取验证码
        initYanZhengMa();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_sure;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.tv_left:
                finish();
                break;
            //发送验证码
            case R.id.tv_yanZhengMa:
                //连接接口,获取验证码
                initYanZhengMa();
                count.start();
                break;
            //确认
            case R.id.bt_sure:
                String code = et_yanZhengMa.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if (TextUtils.isEmpty(code) || TextUtils.isEmpty(password)) {
                    Toast.makeText(this, "验证码和密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password.matches("^[A-Za-z0-9]{6,16}+$")) {
                    Toast.makeText(this, "密码只能是数字、字母以及长度是6-16位", Toast.LENGTH_SHORT).show();
                    return;
                }
                //连接网络,修改密码
                initUpdatePassword(code, password);
                break;
            case R.id.iv_yincang:
                if (click == 0) {
                    this.et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    click = 1;
                } else if (click == 1) {
                    this.et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    click = 0;
                }
                this.et_password.setSelection(this.et_password.getText().toString().length());
                break;
        }
    }

    //连接接口,获取验证码
    private void initYanZhengMa() {

        String url = URLConstant.BASE_URL + "user/sendSMS.do";

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("name", phoneNumber)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.d("Tag", "000000000000");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.d("Tag", "1111111111111");

                String result = null;

                try {
                    result = response.body().string();
                    //Log.d("Tag", result);
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(0);
                }

                parseYanZhengMa(result);
            }
        });
    }

    //解析验证码接口
    private void parseYanZhengMa(String result) {

        Gson gson = new Gson();
        XiuGaiMiMaYZM bean = gson.fromJson(result, XiuGaiMiMaYZM.class);

        if (bean != null) {

            switch (bean.getState()) {
                case 0:
                    mHandler.sendEmptyMessage(1);
                    break;
                case 1:

                    yanZhengMa = bean.getData();

                    mHandler.sendEmptyMessage(2);

                    break;
            }
        }
    }

    //连接网络,修改密码
    private void initUpdatePassword(String et_code, String et_password) {

        String url = URLConstant.BASE_URL + "user/forgetPwd.do";

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("name", phoneNumber)
                .add("newPwd", et_password)
                .add("code", et_code)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.d("Tag", "000000000000");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //Log.d("Tag", "1111111111111");

                String result = null;

                try {
                    result = response.body().string();
                    //Log.d("Tag", result);
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(3);
                }

                parseXiuGaiMiMa(result);
            }
        });
    }

    //解析修改密码数据
    private void parseXiuGaiMiMa(String result) {

        Gson gson = new Gson();
        XiuGaiMiMaSure bean = gson.fromJson(result, XiuGaiMiMaSure.class);

        if (bean != null) {

            switch (bean.getState()) {
                case 0:
                    mHandler.sendEmptyMessage(4);
                    break;
                case 1:
                    mHandler.sendEmptyMessage(5);
                    break;
                case 2:
                case 3:
                case 4:
                    mHandler.sendEmptyMessage(6);
                    break;
            }
        }

    }

    @Override
    protected void onDestroy() {
        count.cancel();
        super.onDestroy();
    }
}
